package com.woniu.learnaop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * created  by woniu201
 * created in 2018/4/6
 */
@Aspect
@Component
public class LogAspect {

    //*  代表任意
    //.. 表示方法的任意参数
    //前置通知
    @Before("execution(public * com.woniu.learnaop.controller.TestController.test(..))")
    public void beforeMethod(JoinPoint joinPoint)
    {
        String  methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("before " + "method: " + methodName + " " + Arrays.asList(args));

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        System.out.println("URI" + request.getRequestURI());
        System.out.println("远程地址：" + request.getRemoteAddr());
    }

    //后置通知
    @After("execution(public * com.woniu.learnaop.controller.TestController.test(..))")
    public void afterMethod(){
        System.err.println("after *************");
    }

    //返回通知,可以访问到方法的返回值
    @AfterReturning(value="execution(public * com.woniu.learnaop.controller.TestController.test(..))"
            ,returning="result")
    public void afterReturning(JoinPoint joinPoint, Object result){
        String  methodName = joinPoint.getSignature().getName();
        System.out.println("return " + "method: " + methodName + "result:" + result);
    }

    //异常通知
    @AfterThrowing(value="execution(public * com.woniu.learnaop.controller.TestController.test(..))",throwing="ex")
    public void afterThrow(JoinPoint joinPoint, Exception ex){
        String  methodName = joinPoint.getSignature().getName();
        System.out.println("throw " + "method: " + methodName + "exception:" + ex);
    }
}
